var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var app = express();

var Config = require('./config');

Config.set('config', app);

var mongoose = Config.get('mongoose');
var session = Config.get('session');
var MongoStore = Config.get('MongoStore');

// view engine setup

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//session 时长为一周,这个是以毫秒为单位,这样我们就建立一个session的会话，这是一个全局的设置
app.use(session({
	secret: 'wechat marry',
	store: new MongoStore({ mongooseConnection: mongoose.connection ,collection:'we_sessions' }),
	resave: false,
	saveUninitialized: false,
	cookie: { maxAge: 1000*3600*24*7 }
}));

require('./routes')(app);

// catch 404 and forward to error handler
/*
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});
*/
// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


//module.exports = app;

/*
 * Socket.io
 */
var port = normalizePort(process.env.PORT || '3000');

function normalizePort(val) {
	var port = parseInt(val, 10);

	if (isNaN(port)) {
		// named pipe
		return val;
	}

	if (port >= 0) {
		// port number
		return port;
	}

	return false;
}


app.set('port', port);

exports.server = require('http').createServer(app).listen(app.get('port'), function() {
	console.log('Wechat Marry Demo started on port %d', app.get('port'));
});

require('./sockets')(app, exports.server);
